//
//  This file is part of iPhoneSMS.
//
//  iPhoneSMS is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  iPhoneSMS is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with iPhoneSMS.  If not, see <http://www.gnu.org/licenses/>.
//
//  MyController.h
//  iPhoneSMS
//
//  Created by Billy Cahill on 1/30/10
//  Copyright 2010 Billy Cahill.
//

#import "MyController.h"
#import "Messages.h"
#import "Conversation.h"

static MyController *inst = nil;
//static double numeric = 10;

@implementation MyController

+(MyController*)controller {
	return inst;
}

-init {
	self = [super init];
	
	m = [[Messages alloc] init];
	
	NSTimeInterval ival = 60.0;
	
	NSDate* next = [NSDate dateWithTimeIntervalSinceNow:ival];
	
	timer = [[NSTimer alloc] initWithFireDate:next interval:ival target:self selector:@selector(doReload:) userInfo:nil repeats:YES];
	
	[lastdate setStringValue: [[timer fireDate] description]];
	
	NSRunLoop* loop = [NSRunLoop currentRunLoop];
	[loop addTimer:timer forMode:NSDefaultRunLoopMode];
	
	inst = self;
	
	return self;
}

-(void)dealloc {
	[m autorelease];
	[timer autorelease];
	
	[super dealloc];
}

- (IBAction)doReload:(id)sender {
	if ( [m reload] ) {
		[tabView reloadData];
		[convTV reloadData];
		
		NSApplication *app = [NSApplication sharedApplication];
		[app requestUserAttention:NSInformationalRequest];
	}
	
	[lastdate setStringValue: [[NSDate date] description]];
}

-(void)handleDoubleClick:sender {
	int row = [tabView clickedRow];
	if ( -1 != row ) {
		NSDictionary* dic = [m objectAtIndex:row];
		[convWind makeKeyAndOrderFront:self];
		
		Conversation* conv = [convTV delegate];
		[conv setPhoneNo:[[dic objectForKey:@"no"] intValue]];
		[conv setMessages:m];
		
		NSString* tit = [NSString stringWithFormat:@"Conversation with %@",
						 [dic objectForKey:@"with"]];
		
		[convWind setTitle:tit];
		[convTV reloadData];
	}
}

-(void)awakeFromNib {
	[tabView setTarget:self];
	[tabView setDoubleAction:@selector(handleDoubleClick:)];
	
	//[updateTicker setDelegate:self];
	[self doReload:nil];
}

- (id)tableView:(NSTableView *)aTableView
objectValueForTableColumn:(NSTableColumn *)aTableColumn
			row:(int)rowIndex  {
    id theRecord, theValue;
	
    NSParameterAssert(rowIndex >= 0 && rowIndex < [m count]);
	
    theRecord = [m objectAtIndex:rowIndex];
	
    theValue = [theRecord objectForKey:[aTableColumn identifier]];
	
    return theValue;
}

- (int)numberOfRowsInTableView:(NSTableView *)aTableView {
    return [m count];
}

- (BOOL)tableView:(NSTableView *)aTableView shouldSelectTableColumn:(NSTableColumn *)aTableColumn {
	NSMutableArray *ary = [m array];
	
	struct mysort_obj obj;
	obj.ctx = [aTableColumn identifier];
	
	NSArray* sorted = [ary sortedArrayUsingFunction:mysort context:&obj];
	BOOL issorted = YES;
	issorted = issorted && ( [[sorted objectAtIndex:0] isEqual:[ary objectAtIndex:0]] );
	issorted = issorted && ( [[sorted objectAtIndex:[sorted count]-1] isEqual:[ary objectAtIndex:[ary count]-1]] );
	
	if ( issorted ) {
		sorted = reverse_ary( ary );
	}
	
	[ary removeAllObjects];
	[ary addObjectsFromArray:sorted];
	
	[aTableView reloadData];
	
	return YES;
}

-(NSString*)getContactdb {
	return [contactdb stringValue];	
}

-(NSString*)getIphoneIp {
	return [iphoneIp stringValue];	
}

-(NSString*)getIphonePort {
	return [iphonePort stringValue];	
}

-(NSDate*)getLastdate {
	return [lastdate dateValue];	
}

-(NSString*)getSmsdb {
	return [smsdb stringValue];	
}

-(double)getUpdateFreq {
	return [updateFreq doubleValue];	
}

-(NSString*)getUsername {
	return [username stringValue];	
}

-(BOOL)control:(NSControl*)ctl isValidObject:obj {
	if ( ctl == updateFreq ) {
		double v = -1;
		NSScanner *s = [NSScanner scannerWithString:[updateFreq stringValue]];
		if ( [s scanDouble:&v] ) {
			return YES;
		}
		return NO;
	}
	
	return YES;
}

- (void)controlTextDidEndEditing:(NSNotification *)aNotification {
	NSControl* ctl = [aNotification object];
	
	if ( ctl == updateFreq ) {
		NSScanner* s = [NSScanner scannerWithString:[updateFreq stringValue]];
		double v = -1;
		if ( [s scanDouble:&v] && v >= 1.0 && v <= 60.0 ) {
			NSDate* dato = [[NSDate alloc] initWithTimeInterval: 60.0*[self getUpdateFreq]sinceDate:[self getLastdate]];
			[timer setFireDate:dato];
			[dato release];
		}
	}
}

@end

NSMutableArray* reverse_ary(NSMutableArray* ary)
{
	NSMutableArray *rv = [[[NSMutableArray alloc] init] autorelease];
	NSEnumerator *emu = [ary reverseObjectEnumerator];
	
	id ob;
	while( ob=[emu nextObject] ) {
		[rv addObject:ob];
	}
	
	return rv;
}

NSInteger mysort(id a, id b, void* ctx) {
	struct mysort_obj *x = (struct mysort_obj*)ctx;
	
	NSString* col = x->ctx;
	NSDictionary *d1, *d2;
	
	d1 = (NSDictionary*)a;
	d2 = (NSDictionary*)b;
	
	NSString* s1 = [d1 objectForKey:col];
	NSString* s2 = [d2 objectForKey:col];
	
	int rv = [s1 compare:s2];
		
	return rv;
}
